<template>
    <el-card style="width: 100%;margin: 0;" shadow="always">
        <template #header>
            <div class="card-header">
                <el-form :inline="true" :model="findForm" class="demo-form-inline">
                    <el-form-item label="审核状态">
                        <el-select v-model="findForm.status" placeholder="请选择" style="width: 200px" clearable>
                            <el-option v-for="item in itemStatusArr" :label="item.label" :value="item.value">
                                <span style="float: left">{{ item.label }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="auditFindAll(findForm)">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </template>
        <el-table :data="auditArr" style="width: 100%" max-height="800" row-key="id"
            :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
            @selection-change="handleSelectionChange" :border="parentBorder"
            :preserve-expanded-content="preserveExpanded">
            <el-table-column type="expand">
                <template #default="props">
                    <el-descriptions :column="3" size="small" class="mt-4">
                        <el-descriptions-item label="项目图片：">
                            <el-image v-if="props.row.itemDate.image" style="width: 100px; height: 100px"
                                :src="props.row.itemDate.image" :preview-src-list="[props.row.itemDate.image]"
                                fit="fill" />
                        </el-descriptions-item>
                        <el-descriptions-item label="项目名称：">
                            {{ props.row.itemDate.name }}
                        </el-descriptions-item>
                        <el-descriptions-item label="项目类型：">{{ props.row.itemDate.type }}</el-descriptions-item>
                        <el-descriptions-item label="负责人：">{{ props.row.itemDate.student }}</el-descriptions-item>
                        <el-descriptions-item label="项目团队：">{{ props.row.itemDate.team }}</el-descriptions-item>
                        <el-descriptions-item label="指导教师：">{{ props.row.itemDate.teacher }}</el-descriptions-item>
                        <el-descriptions-item label="所属学院：">{{ props.row.itemDate.college }}</el-descriptions-item>
                        <el-descriptions-item label="项目文档：">{{ props.row.itemDate.files }}</el-descriptions-item>
                        <el-descriptions-item label="创建日期：">{{ props.row.itemDate.createdAt }}</el-descriptions-item>
                        <el-descriptions-item label="修改日期：">{{ props.row.itemDate.updatedAt }}</el-descriptions-item>
                    </el-descriptions>
                </template>
            </el-table-column>
            <el-table-column type="selection" :selectable="selectable" width="55" />
            <el-table-column property="userName" label="审核人姓名" width="110" />
            <!-- <el-table-column property="itemName" label="项目名称" width="100" /> -->
            <!-- <el-table-column property="status" label="审核状态" width="80">
                <template #default="scope">
                    <el-tag :key="scope.row.status" :type="getItemType(itemStatusArr, scope.row.status)" effect="dark">
                        {{ scope.row.status }}
                    </el-tag>
                </template>
            </el-table-column> -->
            <el-table-column property="text" label="审核信息" width="300" />
            <el-table-column property="auditSize" label="审核次数" width="66" />
            <el-table-column property="createdAt" label="创建日期" width="120" />
            <el-table-column property="updatedAt" label="修改日期" width="120" />
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button v-if="scope.row.status == '审核中'" key="success" type="success"
                        @click="check({ type: '审批', itemName: scope.row.itemName })">审批</el-button>
                    <el-button key="danger" type="danger"
                        @click="check({ type: '驳回', itemName: scope.row.itemName })">驳回</el-button>
                    <el-button v-if="scope.row.status == '已驳回' || scope.row.status == '已通过'" key="primary"
                        type="primary" @click="check({ type: '复审', itemName: scope.row.itemName })">复审</el-button>
                </template>
            </el-table-column>
        </el-table>
        <template #footer>
            <el-button type="warning" round @click="deleteAudit">批量删除</el-button>
        </template>
    </el-card>
    <!-- 添加和修改操作 -->
    <el-drawer v-model="drawerForm" :title="drawerTitle" direction="rtl" size="30%">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="auditForm" :rules="rules" label-width="auto"
            class="demo-ruleForm" status-icon>
            <el-form-item label="审核人姓名">
                <el-input v-model="auditForm.userName" />
            </el-form-item>
            <el-form-item label="项目名称">
                <el-input v-model="auditForm.itemName" />
            </el-form-item>
            <el-form-item label="审核状态">
                <el-select v-model="findForm.status" placeholder="请选择" style="width: 200px" clearable>
                    <el-option v-for="item in itemStatusArr" :label="item.label" :value="findForm.status">
                        <span style="float: left">{{ item.label }}</span>
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="审核建议" prop="text">
                <el-input v-model="auditForm.text" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="updateAudit({ data: auditForm })">
                    提交
                </el-button>
                <el-button @click="drawerForm = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>

</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
// element-plus导入组件
import { ElMessage, ElNotification } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
// 后端接口
import { DeleteListAudit, FindAllAudit, UpdateAudit } from '../../api/audit';
import { FindItemById } from '../../api/item';
import { FindAllItemType } from '../../api/itemType';

import dayjs from "dayjs";

// 页面跳转
import { useRouter } from 'vue-router';
const router = useRouter();
const errorId = sessionStorage.getItem('userRoleId') + ''
if (errorId == undefined || errorId == '' || errorId != '3') {
    sessionStorage.setItem('error', 'not')
    router.push("/LimitsAuthority")
}
const parentBorder = ref(false)
// const childBorder = ref(false)
const preserveExpanded = ref(false)

// 项目状态参数
const itemStatusArr = [
    {
        value: 0,
        label: '草稿',
        type: 'primary',
    },
    {
        value: 1,
        label: '已提交',
        type: 'success',
    },
    {
        value: 2,
        label: '审核中',
        type: 'info',
    },
    {
        value: 3,
        label: '已通过',
        type: 'success',
    },
    {
        value: 4,
        label: '已驳回',
        type: 'danger',
    },
    {
        value: 5,
        label: '已完成',
        type: 'success',
    },
]
// 查询信息参数
const findForm = reactive({
    status: '',
})
// 项目信息
const auditArr = ref([] as any[]);
// 加载审核信息
const auditFindAll = (date: any) => {
    FindAllAudit(date).then((res: any) => {
        if (res.code == 2000) {
            auditArr.value = res.data
            console.log("auditArr---" + res.data.status);
            auditArr.value.forEach((arr: any) => {
                const name = ref('')
                if (arr.itemId != null || arr.itemId != undefined) {
                    FindItemById({ id: arr.itemId }).then((itemRes: any) => {
                        arr.itemDate = itemRes.data
                        arr.itemDate.createdAt = dataFormat(arr.itemDate.createdAt)
                        arr.itemDate.updatedAt = dataFormat(arr.itemDate.updatedAt)
                    })
                }
                itemStatusArr.forEach((sArr: any) => {
                    if (sArr.value == arr.status) {
                        arr.status = sArr.label
                    }
                })
                arr.createdAt = dataFormat(arr.createdAt)
                arr.updatedAt = dataFormat(arr.updatedAt)
                console.log("auditArr---" + arr.status);
            })
        } else {
            ElMessage.error(res.message)
        }
    })
}
auditFindAll(findForm)
// 项目类别
const itemTypeArr = ref([] as any[]);
const itemTypeFindAll = () => {
    FindAllItemType({}).then((res: any) => {
        console.log(res)
        if (res.code == 2000) {
            itemTypeArr.value = res.data
        } else {
            ElMessage.error(res.message)
        }
    })
}
itemTypeFindAll()
// 抽屉参数
const drawerForm = ref(false)
const drawerTitle = ref('')
const openDrawer = (drawerData: string) => {
    drawerForm.value = true
    drawerTitle.value = drawerData
}
// 添加和修改操作
const check = (auditDate: any) => {
    if (auditDate.type == '审批') {
        openDrawer(auditDate.type)
        auditForm.status = '3'
    } else if (auditDate.type == '驳回') {
        openDrawer(auditDate.type)
        auditForm.status = '4'
    } else if (auditDate.type == '复审') {
        openDrawer(auditDate.type)
        auditForm.status = '5'
    }
    auditForm.userName = sessionStorage.getItem('userName') + ''
    auditForm.itemName = auditDate.itemName
}
const updateAudit = (data: any) => {
    if (!ruleFormRef.value) return;
    ruleFormRef.value.validate((valid: boolean) => {
        if (valid) {
            console.log('表单提交成功');
            // 处理添加或更新逻辑
            UpdateAudit(data).then((res: any) => {
                if (res.code == 2000) {
                    ElNotification({
                        title: '成功',
                        message: auditForm.status + '成功',
                        type: 'success',
                    });
                    drawerForm.value = false;
                    auditFindAll(findForm);
                } else {
                    ElMessage.error(res.message);
                }
            });
        } else {
            ElMessage.error('表单校验失败');
        }
    });
}
const selectable = (row: RuleForm) => ![1, 2].includes(row.id)
const multipleSelection = ref<RuleForm[]>([])
const handleSelectionChange = (val: RuleForm[]) => {
    multipleSelection.value = val
}
const deleteAudit = () => {
    let ids = multipleSelection.value.map((item: any) => item.id)
    DeleteListAudit(ids).then((res: any) => {
        if (res.code == 2000) {
            ElNotification({
                title: '成功',
                message: '删除成功',
                type: 'success',
            });
            auditFindAll(findForm);
        } else {
            ElMessage.error(res.message);
        }
    })
}

// 表单验证
interface RuleForm {
    id: number
    userName: string
    status: string
    text: string
    itemName: string,
}

const ruleFormRef = ref<FormInstance>()
const auditForm = reactive<RuleForm>({
    id: 0,
    userName: '',
    status: '',
    text: '',
    itemName: '',
})

const rules = reactive<FormRules<RuleForm>>({
    text: [
        { required: true, message: '请添加项目名称', trigger: 'blur' },
        { min: 8, message: '不能少于8个字', trigger: 'blur' },
    ],
})

// 时间格式化函数
const dataFormat = (data: any) => {
    return dayjs(data).format("YYYY-MM-DD HH:mm:ss");
}
// 遍历数组
const getItemType = (itemTypeArr: any, value: any) => {
    for (let i = 0; i < itemTypeArr.length; i++) {
        console.log("value"+value)
        if (itemTypeArr[i].label == value) {
            return itemTypeArr[i].type
        }
    }
}
</script>

<style scoped>
.box {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    align-items: start;
}

.el-card {
    width: 300px;
    margin: 5px 10px;
}

.card-header {
    display: flex;
    justify-content: space-between;
}

table {
    width: 100%;
    font-size: 16px;
}

table tr {
    width: 100%;
}

table td span {
    width: 120px;
    display: block;
    text-align: right;
    white-space: nowrap;
    /* 防止文本换行 */
    overflow: hidden;
    /* 隐藏溢出的内容 */
    text-overflow: ellipsis;
    /* 在文本溢出时显示省略号。 */
}

.el-upload__tip {
    height: 25px;
    margin: 0;
}

/* 上传图片 */
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
}
</style>